<!-- src/components/plan/SavePlanDialog.vue -->
<template>
  <el-dialog v-model="dialogVisible" title="保存旅游计划" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="计划名称" prop="planName">
        <el-input v-model="form.planName" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status">
          <el-option label="草稿" value="draft" />
          <el-option label="正式" value="official" />
        </el-select>
      </el-form-item>

      <el-form-item label="旅游人数" prop="numPeople">
        <el-input-number v-model="form.numPeople" :min="1" />
      </el-form-item>

      <el-form-item label="平均年龄" prop="avgAge">
        <el-input-number v-model="form.avgAge" :min="1" :max="100" />
      </el-form-item>

      <el-form-item label="预算" prop="budget">
        <el-input-number v-model="form.budget" :min="0" :step="100" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false)
const loading = ref(false)
const form = reactive({
  planName: '',
  status: 'draft',
  numPeople: 1,
  avgAge: 25,
  budget: 0
})

const rules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  numPeople: [{ required: true, message: '请输入旅游人数', trigger: 'blur' }],
  avgAge: [{ required: true, message: '请输入平均年龄', trigger: 'blur' }],
  budget: [{ required: true, message: '请输入预算', trigger: 'blur' }]
}

const emit = defineEmits(['confirm'])

const handleSubmit = async () => {
  const travelersInfo = `${form.numPeople}人，平均年龄${form.avgAge}岁`
  emit('confirm', {
    ...form,
    travelersInfo
  })
  dialogVisible.value = false
}

//导入规划后，填充表单
const prefillForm = (planInfo) => {
  form.planName = planInfo.planName
  form.status = planInfo.status
  // 解析 travelersInfo
  const match = planInfo.travelersInfo?.match(/(\d+)人，平均年龄(\d+)岁/)
  if (match) {
    form.numPeople = parseInt(match[1])
    form.avgAge = parseInt(match[2])
  }
  form.budget = planInfo.budget
}
defineExpose({
  dialogVisible,
  prefillForm
})
</script>